package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(tags = "购物车接口")
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     *
     * 将菜品添加到购物车中
     * @param shoppingCart
     * @return
     */
    @ApiOperation("将菜品添加到购物车中")
    @PostMapping("/add")
    public R save(@RequestBody ShoppingCart shoppingCart) {

        log.info("添加数据到购物车： shoppingCart = {}", shoppingCart);

        ShoppingCart cart = shoppingCartService.add(shoppingCart);

        return R.success(cart);
    }


    /**
     * 根据用户查询所有的购物车信息
     * @return
     */
    @ApiOperation("根据用户查询所有的购物车信息")
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        log.info("查询购物车的所有信息");

        // 根据当前用户查询
        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());
        lambdaQueryWrapper.orderByDesc(ShoppingCart::getCreateTime);

        List<ShoppingCart> shoppingCartList = shoppingCartService.list(lambdaQueryWrapper);

        return R.success(shoppingCartList);
    }


    /**
     * 根据用户清空购物车
     * @return
     */
    @ApiOperation("根据用户清空购物车")
    @DeleteMapping("/clean")
    public R clean() {
        log.info("清空购物车逻辑");

        LambdaQueryWrapper<ShoppingCart> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(ShoppingCart::getUserId, BaseContext.getCurrentId());

        shoppingCartService.remove(lambdaQueryWrapper);

        return R.success();

    }


    /**
     * 减少购物车中商品的数量
     * @param shoppingCart
     * @return
     */
    @ApiOperation("减少购物车中商品的数量")
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart) {
        log.info("需要减少的商品 shoppingCart = {}", shoppingCart);

        ShoppingCart sub = shoppingCartService.sub(shoppingCart);

        return R.success(sub);
    }

}
